/**
 * Copyright (c) 2016-2019 ykf All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.basic.modules.sys.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.basic.common.exception.RRException;
import com.basic.common.utils.MapUtils;
import com.basic.modules.sys.dao.SysUserRoleDao;
import com.basic.modules.sys.entity.SysRoleEntity;
import com.basic.modules.sys.entity.SysUserEntity;
import com.basic.modules.sys.entity.SysUserRoleEntity;
import com.basic.modules.sys.service.SysUserRoleService;
import com.basic.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 用户与角色对应关系
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysUserRoleService")
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleDao, SysUserRoleEntity> implements SysUserRoleService {

    @Lazy
    @Autowired
    private SysUserService userService;

    @Override
    public void saveOrUpdate(Long userId, List<Long> roleIdList) {
        //先删除用户与角色关系
        this.removeByMap(new MapUtils().put("user_id", userId));

        if (roleIdList == null || roleIdList.size() == 0) {
            return;
        }

        //保存用户与角色关系
        for (Long roleId : roleIdList) {
            SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
            sysUserRoleEntity.setUserId(userId);
            sysUserRoleEntity.setRoleId(roleId);

            this.save(sysUserRoleEntity);
        }
    }

    @Override
    public List<Long> queryRoleIdList(Long userId) {
        return baseMapper.queryRoleIdList(userId);
    }

    @Override
    public int deleteBatch(Long[] roleIds) {
        return baseMapper.deleteBatch(roleIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void saveUserRole(SysRoleEntity role) {
        if (ObjectUtil.isEmpty(role) || ObjectUtil.isEmpty(role.getRoleId())) {
            throw new RRException("参数缺失");
        }
        //先删除之前角色绑定的用户
        QueryWrapper<SysUserRoleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserRoleEntity::getRoleId, role.getRoleId());
        this.remove(queryWrapper);
        //保存新的记录
        if (ObjectUtil.isNotEmpty(role.getUserIds())) {
            List<SysUserRoleEntity> saveList = new ArrayList<>();
            for (Long userId : role.getUserIds()) {
                SysUserRoleEntity userRole = new SysUserRoleEntity();
                userRole.setUserId(userId);
                userRole.setRoleId(role.getRoleId());
                saveList.add(userRole);
            }
            this.saveBatch(saveList);
        }
    }

    @Override
    public List<Long> searchDispatchUser(SysRoleEntity role) {
        if (ObjectUtil.isEmpty(role) || ObjectUtil.isEmpty(role.getRoleId())) {
            throw new RRException("参数缺失");
        }
        QueryWrapper<SysUserRoleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserRoleEntity::getRoleId, role.getRoleId());
        List<SysUserRoleEntity> list = this.list(queryWrapper);
        if (ObjectUtil.isNotEmpty(list)) {
            List<Long> userIds = list.stream().map(SysUserRoleEntity::getUserId).collect(Collectors.toList());
            List<SysUserEntity> userList = userService.listByIds(userIds);
            if (ObjectUtil.isNotEmpty(userList)) {
                return userList.stream().map(SysUserEntity::getUserId).collect(Collectors.toList());
            } else {
                return new ArrayList<>();
            }
        }
        return new ArrayList<>();
    }
}
